package web.java.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class GuessServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取用户输入的数字和已经猜的次数
		int count=Integer.parseInt(request.getParameter("count"));
		String num=request.getParameter("number");
		int number=Integer.parseInt(num);
		//游戏结果
		String result=null;
		//创建随机数
		Random random=new Random();
		//得到session
		HttpSession session=request.getSession(false);
		//判断输赢
		if(count>=5){
			//游戏结束
			result="l";
			winOrLose(request,response,result);
			return;
		}
		if(session==null||session.getAttribute("randomNum")==null){
			//第一次猜数字
			int randomNum=random.nextInt(50);
			session=request.getSession();
			session.setAttribute("randomNum",randomNum);
			//比较用户的输入
			if(randomNum>number){
				result="s";
			}else if(randomNum<number){
				result="b";
			}else{
				result="w";
				winOrLose(request,response, result);
				return;
			}
			count++;
			session.setAttribute("result",result);
			request.setAttribute("count",count);
			request.getRequestDispatcher("demo06_guess.jsp").forward(request, response);
			return;
		}
		//一般情况下
		int randomNum=-1;
		randomNum=(Integer)session.getAttribute("randomNum");
		System.out.println(randomNum);
		if(randomNum>number){
			result="s";
		}else if(randomNum<number){
			result="b";
		}else{
			result="w";
			winOrLose(request,response, result);
			return;
		}
		count++;
		session.setAttribute("result",result);
		request.setAttribute("count",count);
		request.getRequestDispatcher("demo06_guess.jsp").forward(request, response);
	}
	public void winOrLose(HttpServletRequest request,HttpServletResponse response, String result) 
			throws ServletException, IOException{
		HttpSession session=request.getSession();
		//移除属性
		request.removeAttribute("count");
		session.setAttribute("result", result);
		//重新指定随机数
		session.removeAttribute("randomNum");
		//转发到jsp
		request.getRequestDispatcher("demo06_guess.jsp").forward(request, response);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req,resp);
	}
}
